{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 数据准备"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "data = pd.read_csv('../utils/dataset/Bike_Sharing_Dataset/day.csv',\n",
    "                   usecols=['season','holiday','weekday','workingday','weathersit','cnt'])\n",
    "mean_data = np.mean(data.iloc[:, -1])    # 目标值的均值\n",
    "# data.sample(5)\n",
    "\n",
    "training_data = data.iloc[:int(0.7*len(data))].reset_index(drop=True)\n",
    "testing_data = data.iloc[int(0.7*len(data)):].reset_index(drop=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 模型基础\n",
    "这里使用方差来作为分裂的依据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2460732.43433013 3741290.119144322 3759494.1914576804 3387461.64666534\n"
     ]
    }
   ],
   "source": [
    "def Var(data, f_name, y_name='cnt'):\n",
    "    f_uni_val = np.unique(data.loc[:, f_name])\n",
    "\n",
    "    # 对每一个可能的特征值做分裂测试并记录分裂后的加权方差\n",
    "    f_var = 0\n",
    "    for val in f_uni_val:\n",
    "        # 把该特征等于某特定值的子集取出来\n",
    "        cutset = data[data.loc[:, f_name] == val].reset_index()\n",
    "        # 加权方差\n",
    "        cur_var = (len(cutset)/len(data))*np.var(cutset.loc[:, y_name], ddof=1)\n",
    "        f_var += cur_var\n",
    "\n",
    "    return f_var\n",
    "\n",
    "\n",
    "# print(Var(data, 'season'),\n",
    "#       Var(data, 'holiday'),\n",
    "#       Var(data, 'weekday'),\n",
    "#       Var(data, 'weathersit'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "def RegTree(data, org_dataset, features, min_instances=5, y_name='cnt', p_node_mean=None):\n",
    "    '''\n",
    "    data：当前用于分裂的数据\n",
    "    org_dataset：最原始的数据集\n",
    "    '''\n",
    "    # 如果数据量小于最小分割量\n",
    "    if len(data) <= int(min_instances):\n",
    "        return np.mean(data.loc[:, y_name])\n",
    "\n",
    "    # 数据为空，返回父节点数据中的目标均值\n",
    "    elif len(data) == 0:\n",
    "        return np.mean(org_dataset.loc[:, y_name])\n",
    "\n",
    "    # 无特征可分，返回父节点均值\n",
    "    elif len(features) == 0:\n",
    "        return p_node_mean\n",
    "\n",
    "    else:\n",
    "        # 当前节点的均值，会被传递给下层函数作为p_node_mean\n",
    "        p_node_mean = np.mean(data.loc[:, y_name])\n",
    "\n",
    "        # 找出最佳(方差最低)分裂特征\n",
    "        f_vars = [Var(data, f) for f in features]\n",
    "        best_f_idx = np.argmin(f_vars)\n",
    "        best_f = features[best_f_idx]\n",
    "\n",
    "        tree = {best_f: {}}\n",
    "\n",
    "        # 移除已分裂的特征\n",
    "        features = [f for f in features if f != best_f]\n",
    "\n",
    "        # 以最佳特征的每一个取值划分数据并生成子树\n",
    "        for val in np.unique(data.loc[:, best_f]):\n",
    "            subset = data.where(data.loc[:, best_f] == val).dropna()\n",
    "            tree[best_f][val] = RegTree(\n",
    "                subset, data, features, min_instances, y_name, p_node_mean)\n",
    "            \n",
    "        return tree\n",
    "    \n",
    "# RegTree(training_data,training_data,training_data.columns[:-1],5,'cnt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict(query,tree,default=mean_data):\n",
    "    '''\n",
    "    query：一个测试样本，字典形式，{f:val,f:val,...}\n",
    "    tree：生成树\n",
    "    default：查找失败时返回的默认值，全样本的目标均值\n",
    "    '''\n",
    "    for feature in list(query.keys()):\n",
    "        if feature in list(tree.keys()):    # 如果该特征与根节点的划分特征相同\n",
    "            try:\n",
    "                sub_tree = tree[feature][query[feature]]    # 根据特征的取值来获取子节点\n",
    "\n",
    "                if isinstance(sub_tree, dict):    # 判断是否还有子树\n",
    "                    return predict(query, sub_tree)    # 有则继续查找\n",
    "                else:\n",
    "                    return sub_tree    # 是叶节点则返回结果\n",
    "            except:    # 没有查到则说明是未见过的情况，只能返回default\n",
    "                return default"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "tree=RegTree(training_data,training_data,training_data.columns[:-1],5)\n",
    "\n",
    "X_test=testing_data.iloc[:,:-1].to_dict(orient = \"records\")\n",
    "Y_test=np.array(testing_data.iloc[:,-1])\n",
    "Y_pred=list()\n",
    "\n",
    "for item in X_test:\n",
    "    Y_pred.append(predict(item,tree))\n",
    "Y_pred=np.array(Y_pred)\n",
    "\n",
    "# print(Y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2353.8730621321206"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def RMSE(Y_true,Y_pred):\n",
    "    return np.sqrt(np.sum(np.square(Y_true-Y_pred))/len(Y_true))\n",
    "\n",
    "RMSE(Y_test,Y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "同样的数据，使用sklearn中的回归树作对比。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2361.6315880780253"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.tree import DecisionTreeRegressor\n",
    "regression_model = DecisionTreeRegressor(criterion=\"mse\",min_samples_leaf=5) \n",
    "regression_model.fit(training_data.iloc[:,:-1],training_data.iloc[:,-1:])\n",
    "predicted = regression_model.predict(testing_data.iloc[:,:-1])\n",
    "\n",
    "RMSE(Y_test,predicted)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
